//
//  NotificationViewController.m
//  MidProject
//
//  Created by itlab on 2020/12/2.
//  Copyright © 2020 itlab. All rights reserved.
//

#import "NotificationViewController.h"

@interface NotificationViewController()
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSDictionary *jsonDictionaryOrArray;
@property(nonatomic,strong) NSArray *items;
@end

@implementation NotificationViewController

-(void) viewDidLoad{
    self.title = @"通知";
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSString *urlString = @"http://172.18.178.56/api/notification/all";
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    NSURLSession *session = [NSURLSession sharedSession];
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    NSError *jsonError;
                                                    self->_jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
                                                    if(jsonError) {
                                                        // check the error description
                                                        NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                    } else {
                                                        // use the jsonDictionaryOrArray
                                                        //                                                  NSLog(@"json : %@",self->_jsonDictionaryOrArray);
                                                        NSLog(@"the length is %lu",self->_jsonDictionaryOrArray.count);
                                                    }
                                                    dispatch_semaphore_signal(semaphore);
                                                }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    
    _items = [self->_jsonDictionaryOrArray valueForKey:@"Notification"];
    //    NSDictionary *array1 = [[_items objectAtIndex:1] objectForKey:@"Data"];
    //    NSLog(@"%@",array1);
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *items = [self->_jsonDictionaryOrArray valueForKey:@"Notification"];
    return items.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // cell的重用标识(*******************不是很懂,不知道是不是为了标识各种不同的cell)
    //    static NSString * cellIdentifier  = @"cell";
    //    // 从重用队列中取出cell对象
    //    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    //    // 如果没有,则创建(解释:一般刚进入界面的时候,是不需要重用的,当时显示的是能够映入界面的足够的cell,只有拖动的时候,才需要)
    //    if (!cell) {
    //        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:cellIdentifier];
    //    }
    //
    static NSString *CellIdentifier = @"Cell";
    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改为以下的方法
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    NSDictionary *array1 = [[_items objectAtIndex:indexPath.row] objectForKey:@"User"];
    NSDictionary *array2 = [[_items objectAtIndex:indexPath.row] objectForKey:@"Data"];
    
    NSString *name = [array1 valueForKey:@"Name"];
    NSString *type = [array2 valueForKey:@"Type"];
    if([type isEqualToString:@"like"]){
        NSString *res = [NSString stringWithFormat:@"%@ 给你点赞了",name];
        cell.textLabel.text = res;
    }else if([type isEqualToString:@"reply"]){
        NSString *res = [NSString stringWithFormat:@"%@ 回复了你",name];
        cell.textLabel.text = res;
    }
    
    NSString *time = [array2 valueForKey:@"CreateTime"];
    NSTimeInterval nsTime = [time doubleValue] / 1000;
    NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:nsTime];
    //    NSLog(@"时间戳 %@",[detaildate description]);
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *date =[formatter stringFromDate:detaildate];
    cell.detailTextLabel.text = date;
    
    NSString *Read = [array2 valueForKey:@"Read"];
    cell.backgroundColor = [UIColor clearColor];
    if([Read boolValue]){
        //表示还未读
        cell.backgroundColor = [UIColor orangeColor];
    }else{
        cell.backgroundColor = [UIColor clearColor];
    }
    
    //    NSLog(@"%@",array1);
    //    NSLog(@"%@",array2);
    
    
    return cell;
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

//设置删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *array = [[_items objectAtIndex:indexPath.row] objectForKey:@"Data"];
    
    NSString *ID = [array valueForKey:@"ID"];
    NSString *Read = [array valueForKey:@"Read"];
    
    if([Read boolValue]){
        //如果该信息是还没有读过的
        NSString *firString = @"http://172.18.178.56/api/notification/read/";
        NSString *urlString = [NSString stringWithFormat:@"%@%@",firString,ID];
        NSDictionary *usernameAndPassword = [[NSDictionary alloc] initWithObjectsAndKeys: @"zhangsan@sysu.edu.cn", @"name", @"test", @"password" ,nil ];
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:usernameAndPassword options:NSJSONWritingPrettyPrinted error:&error];
        NSLog(@"%@",urlString);
        NSURL *url = [NSURL URLWithString:urlString];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [request setHTTPMethod:@"PATCH"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:jsonData];
        NSURLSession *session = [NSURLSession sharedSession];
        dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                    completionHandler:^(NSData *return_data, NSURLResponse *response, NSError *error) {
                                                        
                                                        NSError *jsonError;
                                                        NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:return_data options:kNilOptions error:&jsonError];
                                                        if(jsonError) {
                                                            NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                        } else {
                                                            if ([jsonDictionaryOrArray[@"State"]  isEqual: @"success"]) {
                                                                NSLog(@"json : success");
                                                            } else {
                                                                NSLog(@"json : error");
                                                            }
                                                        }
                                                        dispatch_semaphore_signal(semaphore);
                                                    }
                                          ];
        [dataTask resume];
        dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
        [_tableView reloadData];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        //        [_tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:nil];
    }else{
        //如果该信息是已经读过的
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
        //        cell.backgroundColor = [UIColor orangeColor];
        //        [_tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationFade];
    }
    NSLog(@"完成！");
}

//设置删除按钮的名称
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *array = [[_items objectAtIndex:indexPath.row] objectForKey:@"Data"];
    NSString *Read = [array valueForKey:@"Read"];
    if([Read boolValue]){
        //如果该信息是还没有读过的
        return @"标为已读";
    }else{
        return @"标为未读";
    }
}

@end
